<template>
  <div class="container" v-loading.fullscreen.lock="fullscreenLoading">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>安全管理</el-breadcrumb-item>
      <el-breadcrumb-item>安全隐患管理</el-breadcrumb-item>
      <el-breadcrumb-item>安全隐患清单管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{ nodeRowData ? '编辑' : '新增' }}安全隐患</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="tableColumns">
      <div style="display: flex;align-items: center;margin-left: 80%">
        <el-button @click="addRouter(2, {})" style="margin-left: 10px">取消</el-button>
        <el-button type="primary" @click="handleAddSubmit(mainForm, 1)" style="margin-left: 10px">保存</el-button>
        <el-button type="primary" @click="handlePendding()" style="margin-left: 10px">挂起</el-button>
        <el-button type="primary" @click="handleAssagin()" style="margin-left: 10px">指派</el-button>
      </div>
      <h3>基础信息</h3>
      <el-form ref="mainForm" :rules="rules" :model="ruleForm.mainForm" class="demo-form-inline" label-position="top">
        <div class="content">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="隐患名称" label-width="100px" prop="tshlName">
                <el-input v-model="ruleForm.mainForm.tshlName" placeholder="请输入" style="width: 330px" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="隐患分类" label-width="100px" prop="tshlClassify">
                <el-select filterable v-model="ruleForm.mainForm.tshlClassify" placeholder="请选择" :clearable="true"
                  style="width: 330px">
                  <el-option v-for="item in earlyTypeArr" :key="item.tsharId" :label="item.tsharClassify"
                    :value="item.tsharClassify">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="隐患等级" label-width="100px" prop="tshlGrade">
                <el-select v-model="ruleForm.mainForm.tshlGrade" placeholder="请选择" style="width: 330px">
                  <el-option v-for="item in classTypeArr" :key="item.id" :label="item.value" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="发现时间" label-width="100px" prop="tshlUt">
                <el-date-picker v-model="ruleForm.mainForm.tshlUt" type="date" placeholder="请选择" style="width: 330px"
                  :disabled-date="discoveryOptions" value-format="YYYY-MM-DD" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="问题来源" label-width="100px" prop="sources">
                <el-select v-model="ruleForm.mainForm.sources" placeholder="请选择" filterable style="width: 330px">
                  <el-option v-for="item in organizes" :key="item.id" :label="item.unitName" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="责任单位" label-width="100px" prop="tshlUnit">
                <el-select v-model="ruleForm.mainForm.tshlUnit" placeholder="请选择" style="width: 330px" filterable>
                  <el-option v-for="item in organizes" :key="item.id" :label="item.departName" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="责任人" label-width="100px" prop="tshlPerson">
                <el-input v-model="ruleForm.mainForm.tshlPerson" placeholder="请选择" :clearable="true"
                  style="width: 330px" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="责任人电话" label-width="100px" prop="phone">
                <el-input v-model="ruleForm.mainForm.phone" placeholder="请输入" style="width: 330px" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="整改时限" label-width="100px" prop="tshlLimit">
                <el-date-picker v-model="ruleForm.mainForm.tshlLimit" type="date" placeholder="请选择" :clearable="true"
                  style="width: 330px" :disabled-date="rectifyOptions" value-format="YYYY-MM-DD" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="隐患内容" label-width="100px" prop="content">
                <el-input type="textarea" :rows="3" :clearable="true" v-model="ruleForm.mainForm.content"
                  maxlength="200" show-word-limit placeholder="请输入隐患内容" style="width: 1300px" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="整改要求" :clearable="true" label-width="100px" prop="request">
                <el-input type="textarea" :rows="3" v-model="ruleForm.mainForm.request" maxlength="200" show-word-limit
                  placeholder="请输入整改要求" style="width: 1300px" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <h3 style="margin-bottom: 20px">附件信息</h3>
        <div class="content">
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="上传图片" label-width="100px" class="upload-img" prop="fileListImage"
                :class="imglist.length >= maxImg ? 'div' : ''" ref="uploadRef">
                <el-upload v-model:file-list="imglist" :action="baseGeneralPath + '/file/add'" method="post"
                  list-type="picture-card" class='hide' :limit="maxImg" :on-preview="handlePre"
                  :on-success="handlerUploadSuccess" :on-exceed="handleExceed" :before-upload="handlerBeforeUpload"
                  @change="imagelists" :on-remove="handleRemove">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="上传附件" label-width="100px" prop="filelist" ref="fileUploadRef" :rules="[
    {
      required: true,
      trigger: 'change',
      validator: getfiles,
    },
  ]">
                <el-upload class="upload-demo" drag method="post" :action="baseGeneralPath + '/file/add'" multiple
                  :limit="maxFile" v-model:file-list="filelist" :on-preview="handlePre" :on-success="uploadFileSuccess"
                  :on-exceed="handleFileExceed" :before-upload="fileBeforeUpload" @change="filelists"
                  :on-remove="handleFileRemove">
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <div class="el-upload__text">
                    点击或将文件拖拽到这里上传
                  </div>
                  <template #tip>
                    <div class="el-upload__tip">
                      支持扩展名：{{ fileTypStr }}
                    </div>
                  </template>

                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <edit-dialog :centerDialogVisible="visible" :tilte="dialogTitle" :default-button="false" @Cancel="handleCancel"
        :width="'500px'">

        <template #content>
          <div class="content">
            <el-row :gutter="24" v-if="dialogTitle === '挂起'">
              <el-col :span="24">
                <el-form-item label="挂起原因：" label-width="100px" prop="pendingReason">
                  <el-input type="textarea" :rows="3" :clearable="true" v-model="ruleForm.mainForm.pendingReason"
                    maxlength="200" show-word-limit placeholder="请输入挂起原因" style="width: 500px" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" v-else>
              <el-col :span="24">
                <el-form-item label="责任单位：" label-width="100px" prop="tshlUnit">
                  <el-select v-model="ruleForm.mainForm.tshlUnit" placeholder="请选择" style="width: 500px" filterable>
                    <el-option v-for="item in organizes" :key="item.id" :label="item.departName" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </template>

        <template #custom>
          <span class="dialog-footer">
            <el-button class="buttonCancel" @click="handleCancel"> {{ '取消' }}</el-button>
            <el-button type="primary" class="btn-ok" v-if="dialogTitle === '挂起'"
              @click="handleAddSubmit(mainForm, 5)">挂起</el-button>
            <el-button type="primary" class="btn-ok" v-else @click="handleAddSubmit(mainForm, 2)">确定指派</el-button>
          </span>
        </template>
      </edit-dialog>
      <el-image-viewer v-if="showViewer" @close="showViewer = false" :url-list="[fileUrl]" />
      <preViewFile :visible="showFile" :fileType="fileType" :url="fileUrl" @cancel="showFile = false"></preViewFile>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Plus, UploadFilled } from '@element-plus/icons-vue'
import { rules } from './config/rules'
import CustomTransfer from './components/customTransfer.vue'
import editDialog from '@/components/editDialog/index.vue'
import { baseUrlConfig } from '@/config/config'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, computed, watch, onMounted, reactive } from 'vue'
import moment from 'moment'
import { unitList } from '@/api/secure/recycleUnits'
import { getResource } from '@/api/resource'
import { FormInstance, ElTable, UploadProps } from 'element-plus'
import router from '@/router'
import { useRoute } from 'vue-router'
import { earlyTypeList, appendInventory, inventoryPageList, updateInventory, updateFiles } from '@/api/secure/inventory'
import { useStore } from 'vuex'
const visible = ref(false)
const fullscreenLoading = ref(false)
const route = useRoute()
const { query: { nodeRowData } } = route
import {
  deleteFile,
  deleteFiles,
  downloadFiles,
  onGetFileDownloadPath,
  preViewPdf,
  preViewPPTToPdf,
  uploadFiles,
  uploadKonwledgeFiles
} from "@/api/common"
import preViewFile from '@/components/previewFile/index.vue'
import { findFile } from '../../../../api/secure/inventory'

// 上传图片
const imglist = ref<any[]>([])
const filelist = ref<any[]>([])
// 新增和保存成功后,需要删除的文件的code
var deleteFileCodes = []
// 取消需要删除的文件code
var tempAddFileCodes = []
const baseGeneralPath = baseUrlConfig.businessBaseUrl

// 页面的数据
const ruleForm = reactive({
  loading: false,
  editId: null,
  mainForm: {
    tshlId: null,
    tshlName: null,
    tshlClassify: null,
    tshlGrade: null,
    tshlUt: null,
    sources: null,
    tshlUnit: null,
    tshlPerson: null,
    phone: null,
    tshlLimit: "",
    content: null,
    request: null,
    pictureFile: null,
    accessory: null,
    tshlStat: "1",
    // valid:"1"
  }
})
// 上传文件

interface Option {
  key: number
  label: string
}

const mainForm = ref<FormInstance>()
const multipleTableRef = ref<InstanceType<typeof ElTable>>()
// 监听规则同步等级
watch(() => [ruleForm.mainForm.tshlClassify], (newValue, oldValue) => {
  earlyTypeArr.value.forEach(item => {
    if (newValue == item.tsharClassify) {
      ruleForm.mainForm.tshlClassify = item.tsharClassify
    }
  })
})
// 监听责任单位
watch(() => [ruleForm.mainForm.responsibleUnit], (newValue, oldValue) => {
  // console.log("newValue:"+newValue + " oldValue:" + oldValue)
  if (ruleForm.mainForm.id && oldValue[0] == null) {
    // 编辑,回显首次不联动
  } else {
    organizes.value.forEach(item => {
      if (newValue == item.id) {
        ruleForm.mainForm.person = item.principalName
        ruleForm.mainForm.phone = item.principalPhone
      }
    })
  }

})
//跳转接口
const addRouter = (data: any, row: any) => {
  if (data === 1 && deleteFileCodes.length > 0) {
    excuteDelFile(deleteFileCodes, () => {
      router.push({
        path: '/secure/defect/inventory',
        query: {}
      })
    })
  } else if (data === 2 && tempAddFileCodes.length > 0) {
    // 操作文件并取消
    excuteDelFile(tempAddFileCodes, () => {
      router.push({
        path: '/secure/defect/inventory',
        query: {}
      })
    })

  } else {
    // 无文件操作
    router.push({
      path: '/secure/defect/inventory',
      query: {}
    })
  }

}
const earlyTypeArr = ref([])
/**
 * 获取隐患类型列表
 */
const getEarlyTypeList = () => {
  earlyTypeList({}).then(res => {
    earlyTypeArr.value = []
    let typeArr = [];
    typeArr[0] = res[0];
    let count = 1;
    for (let i = 1; i < res.length; i++) {
      for (let j = 0; j < typeArr.length; j++) {
        if (typeArr[j].tsharClassify == res[i].tsharClassify) {
          break;
        }
      }
      if (j >= typeArr.length) {
        typeArr[count++] = res[i]
      }
    }
    // if (res && res.data) {
    earlyTypeArr.value = typeArr
    // }
  }).catch(e => { })
  // const res=[
  //   {id:1,value:"ssd"},
  //   {id:2,value:"dfd"},
  //   {id:3,value:"djh"}
  // ];
  // earlyTypeArr.value=res
  // earlyTypeArr.value=res;
}
//隐患等级
const classTypeArr = ref<any>([])
const loadDict = async () => {
  // Promise.all([
  //   getResource('tcdm_early_level'),
  // ]).then(([res1]) => {
  //   if (res1?.code === '1') {
  //     classTypeArr.value = res1.data.properties.meta
  //   }
  // })
  const res = [
    { id: 1, value: "一般隐患" },
    { id: 2, value: "严重隐患" },
    { id: 3, value: "较大隐患" },
  ];
  classTypeArr.value = res;
}
// 请求用户的权限树
const { getters } = useStore()
// const organizes = computed(() => getters['user/getOrganTree'])
// 拿到vuex里面用户的信息
const UserInfo = computed(() => getters['user/getUserInfo'])
const organizes = ref([])

const loadUnit = () => {
  unitList().then(res => {
    if (res) {
      organizes.value = res
    }

  }).catch(e => {

  })
}
//添加
const handleAddSubmit = async (formEl: any, type) => {
  if (!formEl) {
    // alert(1111)
    return
  }
  console.log(organizes.value);
  for (let i = 0; i < organizes.value.length; i++) {
    if (organizes.value[i].id == ruleForm.mainForm.tshlUnit) {
      ruleForm.mainForm.tshlUnit = organizes.value[i].departName;
    }
  }
  await formEl.validate(async (valid: any) => {
    // alert(111)
    // if (valid) {
    // 判断新增或编辑
    if (ruleForm.mainForm.pictureFile?.length == 0) {
      // 置空
      ruleForm.mainForm.pictureFile = null
    }
    if (!ruleForm.mainForm.tshlLimit) {
      // 置空
      ruleForm.mainForm.tshlLimit = ""
    }
    var msgType = dialogTitle.value ? dialogTitle.value : '保存'
    if (ruleForm.mainForm.tshlId) {
      // 修改
      ruleForm.mainForm.tshlStat = type;
      // ruleForm.mainForm.valid='1'
      updateInventory(ruleForm.mainForm).then(res => {
        if (res) {
          // console.log(res);
          // console.log(ruleForm.mainForm.pictureFile[0]);
          if (ruleForm.mainForm.pictureFile != null) {
            for (let i = 0; i < ruleForm.mainForm.pictureFile.length; i++) {
              ruleForm.mainForm.pictureFile[i].tshlId = res.tshlId
              updateFiles(ruleForm.mainForm.pictureFile[i]).then(res => {
                // console.log(res);
              })
            }
          }
          if (ruleForm.mainForm.accessory != null) {
            for (let i = 0; i < ruleForm.mainForm.accessory.length; i++) {
              ruleForm.mainForm.accessory[i].tshlId = res.tshlId
              updateFiles(ruleForm.mainForm.accessory[i]).then(res => {
                // console.log(res);
              })
            }
          }
          // ruleForm.mainForm.pictureFile[0].tshlId=res.tshlId
          // console.log(ruleForm.mainForm.pictureFile[0].tshlId);

          ElMessage.success(msgType + '成功')
          addRouter(1, {})
        } else {
          ElMessage.error(msgType + '失败')
        }
      }).catch(e => {
        ElMessage.error('服务器错误,请联系管理员')
      })
    } else {
      // ruleForm.mainForm.valid='1'
      // ruleForm.mainForm.createUserid = UserInfo.value.userId
      appendInventory(ruleForm.mainForm).then(res => {
        //弹框
        if (res) {
          // console.log(res);
          // console.log(ruleForm.mainForm.pictureFile[0]);
          if (ruleForm.mainForm.pictureFile != null) {
            for (let i = 0; i < ruleForm.mainForm.pictureFile.length; i++) {
              ruleForm.mainForm.pictureFile[i].tshlId = res.tshlId
              updateFiles(ruleForm.mainForm.pictureFile[i]).then(res => {
                // console.log(res);
              })
            }
          }
          if (ruleForm.mainForm.accessory != null) {
            for (let i = 0; i < ruleForm.mainForm.accessory.length; i++) {
              ruleForm.mainForm.accessory[i].tshlId = res.tshlId
              updateFiles(ruleForm.mainForm.accessory[i]).then(res => {
                // console.log(res);
              })
            }
          }
          // ruleForm.mainForm.pictureFile[0].tshlId=res.tshlId
          // console.log(ruleForm.mainForm.pictureFile[0].tshlId);

          ElMessage.success(msgType + '成功')
          addRouter(1, {})
        } else {
          ElMessage.error(msgType + '失败')
        }
      }).catch(e => {
        // ElMessage.error('服务器错误,请联系管理员')
        // console.log(459);

      })

      // }
    }
  })
}
// 回显编辑
const loadRow = async () => {
  debugger
  if (nodeRowData) {
    // fullscreenLoading.value = true
    const params = {
      page: {
        page: 0,
        size: 1,
      },
      tcdmSecureHazardList: {
        tshlId: nodeRowData
      },
      myTime2: {
        startTime: null,
        endTime: null
      }
    }
    const pictureParam = {
      tshlId: nodeRowData,
      fileLocation: 1
    }
    const accessoryParam = {
      tshlId: nodeRowData,
      fileLocation: 2
    }
    const res = await inventoryPageList(params)
    console.log(res.content);
    const pic = await findFile(pictureParam)
    const acc = await findFile(accessoryParam)
    //像后端条件查询数据
    // if (res.content.length>0) {
    // 信息列表数据
    console.log(res.content);
    // alert(1)
    console.log(res.content[0]);
    ruleForm.mainForm = res.content[0]
    console.log(ruleForm.mainForm)


    // console.log(ruleForm.mainForm);
    // ruleForm.mainForm.pictureFile= null;
    // ruleForm.mainForm.accessory=null;
    // ruleForm.mainForm.isState= "1";
    // ruleForm.editId=
    //通过清单的id查找当前id下的文件然后将当前获得的数据遍历

    ruleForm.mainForm.pictureFile = pic.map((item: any) => {
      return {
        fileId: item.fileId,
        fileName: item.fileName,
        fileSize: item.fileSize,
        filePath: item.filePath,
        fileType: item.fileType,
        fileLocation: item.fileLocation,
        tshlId: item.tshlId
      }
    }) || []
    // console.log(ruleForm.mainForm.pictureFile);

    ruleForm.mainForm.accessory = acc.map((item: any) => {
      return {
        fileId: item.fileId,
        fileName: item.fileName,
        fileSize: item.fileSize,
        filePath: item.filePath,
        fileType: item.fileType,
        fileLocation: item.fileLocation,
        tshlId: item.tshlId
      }
    }) || []
    // ruleForm.mainForm.accessory = res.data.list[0].accessory?.map((item: any) => {
    //   return {
    //     enclosureCode: item.enclosureCode,
    //     enclosureContent: item.enclosureContent,
    //     enclosureName: item.enclosureName,
    //     enclosureSuffix: item.enclosureSuffix,
    //     resourceAddress: item.resourceAddress,
    //     name: item.enclosureName + '.' + item.enclosureSuffix
    //   }
    // }) || []

    ruleForm.mainForm.pictureFile.forEach((item: any) => {
      // item.url = (useImgurl(item.filePath))
      // let path = item.filePath
      // let name = path.substring(path.lastIndexOf("\\") + 1);

      // item.url = path.substring(0, path.lastIndexOf("\\") + 1).replace("D:\\file", "/file") + encodeURI(name);
      item.url = item.filePath;
      // console.log(item.url);
    })

    ruleForm.mainForm.accessory.forEach((item: any) => {
      // item.url = (useImgurl(item.resourceAddress))
      item.url = item.filePath;
      item.name = item.fileName;
    })

    imglist.value = ruleForm.mainForm.pictureFile
    filelist.value = ruleForm.mainForm.accessory

    imgTempFile.value = ruleForm.mainForm.pictureFile
    tempFile.value = ruleForm.mainForm.accessory

    fullscreenLoading.value = false
  }
  // else {

  // }}
}
const dialogTitle = ref('')
const handlePendding = () => {
  visible.value = true
  dialogTitle.value = '挂起'
}
const handleAssagin = () => {
  visible.value = true
  dialogTitle.value = '指派'
}
const handleCancel = () => {
  ruleForm.mainForm.pendingReason = ''
  ruleForm.mainForm.assignUnit = ''
  visible.value = false
}
const maxFile = ref(5)
const maxImg = ref(5)
const getfiles = (rule: any, value: any, callback: any) => {
  if (!filelist.value.length) {
    callback('请上传附件')
  }
  callback()
}
const downloadFile = async (uploadFile: any) => {
  var enclosureCode = ''
  var fileName = ''
  enclosureCode = uploadFile.enclosureCode
  fileName = uploadFile.enclosureName + '.' + uploadFile.enclosureSuffix
  if (!enclosureCode) {
    ElMessage.error(`文件地址不存在`)
    return
  }
  try {
    const res = await downloadFiles(enclosureCode)
    const blob = new Blob([res], { type: 'application/octet-stream' })
    const a = document.createElement("a")
    const objectUrl = URL.createObjectURL(blob)
    a.href = objectUrl
    a.download = fileName
    a.click()
    URL.revokeObjectURL(a.href)
  } catch (e) {
    ElMessage.error(`下载失败`)
  }
}
//上传成功
interface FileFace {
  fileId: Number
  fileName: string
  fileSize: string
  filePath: string
  fileType: string
  fileLocation: Number
}
const imgTempFile = ref<Array<any>>([])
const tempFile = ref<Array<any>>([])
const hideImgUpload = ref(false)
const hideFileUpload = ref(false)
// 图片上传成功
const handlerUploadSuccess: UploadProps['onSuccess'] = (resp, uploadFile, uploadFiles) => {
  console.log(resp, uploadFile, uploadFiles)
  if (resp) {
    const item: FileFace = {
      fileId: resp.fileId,
      fileName: resp.fileName,
      fileSize: resp.fileSize,
      filePath: resp.filePath,
      fileType: resp.fileType,
      fileLocation: 1,
      tshlId: null
    }
    // tempAddFileCodes.push(item.enclosureCode)
    imgTempFile.value.push(item)
    // console.log(imgTempFile.value)
    ruleForm.mainForm.pictureFile = imgTempFile.value
    if (imgTempFile.value.length >= maxImg.value) {
      hideImgUpload.value = true
    }
  }
}
// 文件上传成功
const uploadFileSuccess: UploadProps['onSuccess'] = (resp, uploadFile, uploadFiles) => {
  console.log(resp, uploadFile, uploadFiles)
  // if (resp?.code === '1') {
  const item: FileFace = {
    fileId: resp.fileId,
    fileName: resp.fileName,
    fileSize: resp.fileSize,
    filePath: resp.filePath,
    fileType: resp.fileType,
    fileLocation: 2,
    tshlId: null
  }
  // tempAddFileCodes.push(item.enclosureCode)
  tempFile.value.push(item)
  // console.log(fileTempFile.value)
  ruleForm.mainForm.accessory = tempFile.value
  if (tempFile.value.length >= maxFile.value) {
    hideFileUpload.value = true
  }

  // }
}
// 超出警告框
const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage.error('上传图片数不能超过' + maxImg.value + '个')

}
const handleFileExceed: UploadProps['onExceed'] = () => {
  ElMessage.error('上传文件数不能超过' + maxFile.value + '个')
}

// 图上传前
const handlerBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // console.log(rawFile)
  const fileSuffix = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)

  const whiteList = ['jpg', 'png', 'JPG', 'PNG']
  if (whiteList.indexOf(fileSuffix) === -1) {
    ElMessage.error('上传图片类型只能是 jpg,png格式')
    return false
  }

  if (rawFile.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小只能在10M以内')
    return false
  }

}
const fileTypStr = ref('rar,zip,doc,docx,pdf,xlsx,xls,ppt,pptx,txt,mp4,wms,png,jpg')
// 文件上传前
const fileBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // console.log(rawFile)
  const fileSuffix = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)
  const whiteList = fileTypStr.value.split(',').concat(fileTypStr.value.toUpperCase().split(','))
  if (whiteList.indexOf(fileSuffix) === -1) {
    ElMessage.error('上传文件类型只能是' + fileTypStr.value + '格式')
    return false
  }

  if (rawFile.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小只能在10M以内')
    return false
  }

}
const uploadRef = ref()
const fileUploadRef = ref()
const filelists = async () => {
  if (!filelist.value.length) {
    fileUploadRef.value.clearValidate()
  }

}
const imagelists = async () => {
  if (!imglist.value.length) {
    uploadRef.value.clearValidate()
  }

}
const delFile = (code: string) => {
  deleteFileCodes.push(code)
}
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  let code = ''
  if (uploadFile.name) {
    code = uploadFile.fileId
  } else {
    code = uploadFile.fileId
  }
  ruleForm.mainForm.pictureFile = ruleForm.mainForm.pictureFile.filter(item => item.fileId != code)
  delFile(code)
  hideImgUpload.value = false
  imgTempFile.value = imgTempFile.value.filter(item => item.fileId != code)
}
const handleFileRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  let code = ''
  if (!uploadFile.url) {
    code = uploadFile.fileId
  } else {
    code = uploadFile.fileId
  }
  ruleForm.mainForm.accessory = ruleForm.mainForm.accessory.filter(item => item.fileId != code)
  delFile(code)
  hideFileUpload.value = false
  tempFile.value = tempFile.value.filter(item => item.fileId != code)
}
const useImgurl = (url: string) => {
  const imgUrls = '/general-business'
  if (url.includes('/filePath')) {
    url = url.replace('/filePath', '')
  }
  if (url.includes('/api')) {
    url = url.replace('/api', '')
  }
  if (url.includes('/general-business')) {
    url = url.replace('/general-business', '')
  }
  return imgUrls + url
}
const excuteDelFile = (codes, callback) => {
  console.log(codes)
  if (codes != null) {
    for (let i = 0; i < codes.length; i++) {
      let data = {
        fileId: codes[i]
      }
      deleteFiles(data).then(res => {
        if (res) {
          deleteFileCodes = []
          tempAddFileCodes = []
          callback()
        }
      }).catch(e => {
        ElMessage.error('文件保存异常')
      })
    }
  }
}

const discoveryOptions = (time) => {
  return time.getTime() > Date.now()
}

const rectifyOptions = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}
/**
 * 预览
 */
const fileUrl = ref()
const fileType = ref()
const showFile = ref(false)
const showViewer = ref(false)
const handlePre = async (data: any) => {
  fullscreenLoading.value = true
  if (data.response) {
    data = data.response.data
  }
  try {
    if (data.enclosureSuffix != 'pdf' && !/(.jpg|.jpeg|.png|.gif|.bmp|.svg)/.test(data.url)
      && (data.enclosureSuffix != 'xls' && data.enclosureSuffix != 'xlsx')) {
      // 非图片和表格和pdf转 为pdf
      preViewPdf(data.enclosureCode).then(res => {
        // console.log(res)
        const blob = new Blob([res], { type: "application/pdf" })
        fileUrl.value = URL.createObjectURL(blob)
        fileType.value = 'pdf'
        showFile.value = true
        fullscreenLoading.value = false
      }).catch(e => {
        fullscreenLoading.value = false
        ElMessageBox.confirm(
          '当前文件不支持预览,是否下载?',
          '确认',
          {
            cancelButtonText: '取消',
            confirmButtonText: '下载',
            type: 'warning'
          }
        ).then(() => {
          downloadFile(data)
        }).catch(() => {
        })
      })
    } else if (data.enclosureSuffix == 'xls' || data.enclosureSuffix == 'xlsx') {
      fullscreenLoading.value = false
      ElMessageBox.confirm(
        '当前文件不支持预览,是否下载?',
        '确认',
        {
          cancelButtonText: '取消',
          confirmButtonText: '下载',
          type: 'warning'
        }
      ).then(() => {
        downloadFile(data)
      }).catch(() => {
      })
    } else {
      onGetFileDownloadPath(data.enclosureCode).then(res => {
        fullscreenLoading.value = false
        // console.log(res)
        if (data.enclosureSuffix == 'pdf') {
          const blob = new Blob([res], { type: "application/pdf" })
          fileUrl.value = URL.createObjectURL(blob)
          fileType.value = 'pdf'
          showFile.value = true
        } else {
          const blob = new Blob([res], { type: "application/png" })
          fileUrl.value = URL.createObjectURL(blob)
          showViewer.value = true
        }
      }).catch(e => {
        fullscreenLoading.value = false
        ElMessageBox.confirm(
          '当前文件不支持预览,是否下载?',
          '确认',
          {
            cancelButtonText: '取消',
            confirmButtonText: '下载',
            type: 'warning'
          }
        ).then(() => {
          downloadFile(data)
        }).catch(() => {
        })
      })
    }
  } catch (e) {
    fullscreenLoading.value = false
    ElMessageBox.confirm(
      '当前文件不支持预览,是否下载?',
      '确认',
      {
        cancelButtonText: '取消',
        confirmButtonText: '下载',
        type: 'warning'
      }
    ).then(() => {
      downloadFile(data)
    }).catch(() => {
    })
  }
}
onMounted(() => {
  loadUnit()
  loadDict()
  getEarlyTypeList()
  loadRow()
})
</script>

<style lang="less" scoped>
/deep/.el-upload.is-drag {
  width: 370px;
  height: 200px !important;
}

//@import "../style/publicStyle.less";
/deep/ .elTable .cell {
  white-space: pre-line !important;
  text-align: center;
  padding: 0;
  margin: 0;
  width: 100% !important;
}

/deep/ .elTable .el-table__cell {
  padding: 0;
  margin: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
}

/deep/ .el-input__suffix {
  display: none;
}

.el-breadcrumb {
  padding: 12px 24px;
  line-height: 22px;
}

/deep/ .el-breadcrumb__inner {
  color: #989DAA;
}

.container {
  background: #fff;

  .tableColumns {
    /* max-height: 1250px; */

    /* min-height: 1080px; */
    flex-direction: column;
    background-color: #FFF;
    margin: 0 15px;
    padding: 12px 24px;
    border-radius: 5px;
    position: relative;

    .content {
      width: 90%;
      margin: 10px auto;

    }
  }

  /deep/ .headerClass {
    background: #F3F5F9 !important;

    th.el-table__cell {
      background: #F3F5F9 !important;
    }
  }

  .el-form-item {
    display: flex !important;
  }
}

/deep/ .el-form--default.el-form--label-top .el-form-item .el-form-item__label {
  width: 95px;
  text-align: right;
  margin-bottom: 0;
  margin-top: 5px;
}

/deep/ .el-col {
  margin-bottom: 5px;
}
</style>
